<template>
  <div class="docker-image-manager">
    <!-- 顶部操作区 -->
    <div class="header-actions">
      <h2>Docker镜像管理</h2>
      <div class="actions">
        <button @click="syncAliyunImages" :disabled="syncing" class="btn btn-primary">
          {{ syncing ? '同步中...' : '同步阿里云镜像' }}
        </button>
        <button @click="showAddImageModal = true" class="btn btn-secondary">
          添加自定义镜像
        </button>
      </div>
    </div>

    <!-- 镜像列表 -->
    <div class="images-list">
      <div class="table-container">
        <table class="images-table">
          <thead>
            <tr>
              <th>镜像名称</th>
              <th>仓库地址</th>
              <th>当前版本</th>
              <th>描述</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(image, index) in images" :key="`${image.name}-${image.current_version}-${index}`" class="image-row">
              <td class="image-name">{{ image.name }}:{{ image.current_version }}</td>
              <td class="registry">{{ image.registry }}</td>
              <td class="version">{{ image.current_version }}</td>
              <td class="description">{{ image.description }}</td>
              <td class="status">
                <span :class="['status-badge', image.enabled ? 'enabled' : 'disabled']">
                  {{ image.enabled ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="actions">
                <button 
                  @click="pullImage(image)" 
                  :disabled="pulling[`${image.name}:${image.current_version}`]"
                  class="btn btn-sm btn-primary"
                >
                  {{ pulling[`${image.name}:${image.current_version}`] ? '拉取中...' : '拉取镜像' }}
                </button>
                <button 
                  @click="removeImage(`${image.name}:${image.current_version}`)" 
                  class="btn btn-sm btn-danger"
                  v-if="!isHardcodedImage(image.name)"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加镜像模态框 -->
    <div v-if="showAddImageModal" class="modal-overlay" @click="closeAddImageModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>添加自定义镜像</h3>
          <button @click="closeAddImageModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="addCustomImage">
            <div class="form-group">
              <label>镜像名称 *</label>
              <input 
                v-model="newImage.name" 
                type="text" 
                placeholder="例如: mobox-docker/custom-service"
                required
              >
            </div>
            <div class="form-group">
              <label>仓库地址</label>
              <input 
                v-model="newImage.registry" 
                type="text" 
                placeholder="默认使用阿里云仓库"
              >
            </div>
            <div class="form-group">
              <label>版本标签</label>
              <input 
                v-model="newImage.version" 
                type="text" 
                placeholder="latest"
              >
            </div>
            <div class="form-group">
              <label>描述</label>
              <input 
                v-model="newImage.description" 
                type="text" 
                placeholder="镜像描述信息"
              >
            </div>
            <div class="form-group">
              <label>
                <input 
                  v-model="newImage.auto_update" 
                  type="checkbox"
                > 
                自动更新
              </label>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button @click="closeAddImageModal" class="btn btn-secondary">取消</button>
          <button @click="addCustomImage" :disabled="addingImage" class="btn btn-primary">
            {{ addingImage ? '添加中...' : '添加镜像' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 状态消息 -->
    <div v-if="message" :class="['message', messageType]">
      {{ message }}
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'

export default {
  name: 'DockerImageManager',
  setup() {
    const images = ref([])
    const syncing = ref(false)
    const pulling = reactive({})
    const showAddImageModal = ref(false)
    const addingImage = ref(false)
    const message = ref('')
    const messageType = ref('info')

    const newImage = reactive({
      name: '',
      registry: 'crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com',
      version: 'latest',
      description: '',
      auto_update: false
    })

    // 硬编码的核心镜像名单
    const hardcodedImages = [
      'mobox-docker/blocky',
      'mobox-docker/vue-ai-base',
      'mobox-docker/jupyter'
    ]

    const showMessage = (msg, type = 'info') => {
      message.value = msg
      messageType.value = type
      setTimeout(() => {
        message.value = ''
      }, 3000)
    }

    const isHardcodedImage = (imageName) => {
      return hardcodedImages.includes(imageName)
    }

    const loadImages = async () => {
      try {
        const response = await fetch('/api/docker/images/config')
        const data = await response.json()
        if (data.images) {
          images.value = data.images
        }
      } catch (error) {
        showMessage('加载镜像列表失败', 'error')
        console.error('加载镜像列表失败:', error)
      }
    }

    const syncAliyunImages = async () => {
      syncing.value = true
      try {
        const response = await fetch('/api/docker/images/sync-aliyun', {
          method: 'POST'
        })
        const data = await response.json()
        if (data.success) {
          showMessage(data.message, 'success')
          await loadImages()
        } else {
          showMessage(data.message || '同步失败', 'error')
        }
      } catch (error) {
        showMessage('同步请求失败', 'error')
        console.error('同步失败:', error)
      } finally {
        syncing.value = false
      }
    }

    const pullImage = async (image) => {
      const imageKey = `${image.name}:${image.current_version}`
      pulling[imageKey] = true
      try {
        const response = await fetch('/api/docker/images/pull-direct', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            image_name: image.name,
            registry: image.registry,
            version: image.current_version || 'latest'
          })
        })
        const data = await response.json()
        if (data.success) {
          showMessage(`开始拉取 ${imageKey}`, 'success')
        } else {
          showMessage(data.error || '拉取失败', 'error')
        }
      } catch (error) {
        showMessage('拉取请求失败', 'error')
        console.error('拉取失败:', error)
      } finally {
        pulling[imageKey] = false
      }
    }

    const addCustomImage = async () => {
      if (!newImage.name.trim()) {
        showMessage('请输入镜像名称', 'error')
        return
      }

      addingImage.value = true
      try {
        const response = await fetch('/api/docker/images/config/add', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: newImage.name,
            registry: newImage.registry,
            current_version: newImage.version,
            description: newImage.description,
            auto_update: newImage.auto_update,
            enabled: true
          })
        })
        const data = await response.json()
        if (data.success) {
          showMessage('镜像配置添加成功', 'success')
          await loadImages()
          closeAddImageModal()
        } else {
          showMessage(data.error || '添加失败', 'error')
        }
      } catch (error) {
        showMessage('添加请求失败', 'error')
        console.error('添加失败:', error)
      } finally {
        addingImage.value = false
      }
    }

    const removeImage = async (imageName) => {
      if (!confirm(`确定要删除镜像配置 "${imageName}" 吗？`)) {
        return
      }

      try {
        const response = await fetch(`/api/docker/images/config/${encodeURIComponent(imageName)}`, {
          method: 'DELETE'
        })
        const data = await response.json()
        if (data.success) {
          showMessage('镜像配置删除成功', 'success')
          await loadImages()
        } else {
          showMessage(data.error || '删除失败', 'error')
        }
      } catch (error) {
        showMessage('删除请求失败', 'error')
        console.error('删除失败:', error)
      }
    }

    const closeAddImageModal = () => {
      showAddImageModal.value = false
      // 重置表单
      Object.assign(newImage, {
        name: '',
        registry: 'crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com',
        version: 'latest',
        description: '',
        auto_update: false
      })
    }

    onMounted(() => {
      loadImages()
    })

    return {
      images,
      syncing,
      pulling,
      showAddImageModal,
      addingImage,
      message,
      messageType,
      newImage,
      isHardcodedImage,
      loadImages,
      syncAliyunImages,
      pullImage,
      addCustomImage,
      removeImage,
      closeAddImageModal
    }
  }
}
</script>

<style scoped>
.docker-image-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.header-actions h2 {
  margin: 0;
  color: #333;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #545b62;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background-color: #c82333;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.images-table {
  width: 100%;
  border-collapse: collapse;
}

.images-table th,
.images-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.images-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.image-row:hover {
  background-color: #f8f9fa;
}

.image-name {
  font-family: monospace;
  font-weight: 500;
}

.registry {
  font-family: monospace;
  font-size: 12px;
  color: #6c757d;
}

.version {
  font-family: monospace;
  background-color: #e9ecef;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.enabled {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.disabled {
  background-color: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 5px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-group input[type="text"] {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input[type="text"]:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-group input[type="checkbox"] {
  margin-right: 8px;
}

/* 消息样式 */
.message {
  padding: 12px;
  border-radius: 4px;
  margin-top: 20px;
  font-weight: 500;
}

.message.info {
  background-color: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
</style> 